package com.addplus.townmall.server.queue.serviceimpl;

import com.addplus.townmall.server.api.constant.ErrorCode;
import com.addplus.townmall.server.api.mapper.town.MemberMapper;
import com.addplus.townmall.server.api.model.town.Member;
import com.addplus.townmall.server.api.model.town.param.AliyunMsmSingleParam;
import com.addplus.townmall.server.api.modelenum.PlatformEnum;
import com.addplus.townmall.server.api.constant.StringConstant;
import com.addplus.townmall.server.api.exception.ErrorException;
import com.addplus.townmall.server.api.mapper.town.AppMessageRecordMapper;
import com.addplus.townmall.server.api.model.town.AppMessageRecord;
import com.addplus.townmall.server.api.modelenum.QueueEnum;
import com.addplus.townmall.server.api.service.queue.AsyncService;
import com.addplus.townmall.server.api.utils.DataUtils;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service(interfaceClass = AsyncService.class, async = true,executes = 1)
public class AsyncServiceImpl implements AsyncService{

    @Autowired
    private AppMessageRecordMapper appMessageRecordMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MemberMapper memberMapper;

    @Value("${sms.accessKeyId}")
    private String accessKeyId;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${sms.accessKeySecret}")
    private String accessKeySecret;

    @Override
    public void sendAliYunMessage(PlatformEnum platformEnum, String phone, String code, Integer type) throws Exception{
        AliyunMsmSingleParam aliyunMsmSingleParam = new AliyunMsmSingleParam();
        aliyunMsmSingleParam.setCode(code);
        aliyunMsmSingleParam.setPhone(phone);
        aliyunMsmSingleParam.setPlatformEnum(platformEnum);
        aliyunMsmSingleParam.setType(type);
        rabbitTemplate.convertAndSend(QueueEnum.MSM_QUEUW.getExchange(),QueueEnum.MSM_QUEUW.getRoutingKey(),aliyunMsmSingleParam);
    }


    @Override
    public void batchAliYunMessage(List<Integer> memberIdList, String templateCode, List<JSONObject> jsonObject) throws Exception {
        if (memberIdList==null||memberIdList.size()==0||templateCode==null||jsonObject==null||jsonObject.size()==0){
            throw new ErrorException(ErrorCode.SYS_ERROR_PARAM);
        }
        List<String> singNameList=new ArrayList<>();
        singNameList.add(StringConstant.ALIYUN_SMS_SIGNNAME);
        String signNameJson= JSONUtils.toJSONString(singNameList);
        IClientProfile profile = DefaultProfile.getProfile(StringConstant.ALIYUN_SMS_REGIONID,accessKeyId,accessKeySecret);
        DefaultProfile.addEndpoint(StringConstant.ALIYUN_SMS_REGIONID, StringConstant.ALIYUN_SMS_REGIONID,StringConstant.ALIYUN_SMS_PRODUCT,
                                    StringConstant.ALIYUN_SMS_DOMAIN);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        SendBatchSmsRequest request = new SendBatchSmsRequest();
        request.setMethod(MethodType.POST);
        //必填:短信签名-可在短信控制台中找到"[\"云通信\",\"云通信\"]"
        request.setSignNameJson(signNameJson);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //必填:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        request.setTemplateParamJson(JSONUtils.toJSONString(jsonObject));
        //请求失败这里会抛ClientException异常
        List<Member> members = memberMapper.selectBatchIds(memberIdList);
        List<String> phoneNumberList= new ArrayList<>();
        for (int i = 0; i < members.size(); i++) {
            phoneNumberList.add(members.get(i).getCellPhone());
        }
        SendBatchSmsResponse sendSmsResponse=null;
        //必填:待发送手机号。支持JSON格式的批量调用，批量上限为100个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
        int phoneListSize=phoneNumberList.size();
        List<String> countPhoneList=new ArrayList<>();
        for (int i = 0; i < phoneListSize; i++) {
            countPhoneList.add(phoneNumberList.get(i));
            if (phoneListSize==i+1||i+1/100==0){
                String phoneNumberJson = JSONUtils.toJSONString(countPhoneList);
                request.setPhoneNumberJson(phoneNumberJson);
                sendSmsResponse= acsClient.getAcsResponse(request);
                countPhoneList.clear();
            }
//            System.out.printf(sendSmsResponse.getCode());
//            if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
//                System.out.println("chegngong");
//            }
        }
    }
}
